const { MicroApp } = require('../../model');
// 微应用配置
const addMicroApp = async (req, res) => {
  console.log('添加微应用配置');
  // 解析token
  // const {
  //   headers: { authorization },
  // } = req;

  // const token = Token.decrypt(authorization);
  const { name, entry, activeRule, code, childProps = {} } = req.body;
  console.log({ name, entry, activeRule, code });
  try {
    const [MicroInfo, flag] = await MicroApp.findOrCreate({ where: { entry, code }, defaults: { name, entry, activeRule, childProps: childProps } });
    if (flag) {
      res.send({ errcode: 0, msg: 'ok', success: true });
    } else {
      res.send({ errcode: 1, msg: '已存在，请勿重复添加', success: false });
    }
  } catch (error) {
    console.log('服务错误:', error);
    res.send({ errcode: 1, msg: '添加失败' + error, success: false });
  }
};

const getMicroAppList = async (req, res) => {
  console.log('查找微应用配置');
  // 解析token
  // const {
  //   headers: { authorization },
  // } = req;

  // const token = Token.decrypt(authorization);
  // const { name, entry, activeRule, childProps } = req.body;
  try {
    const list = await MicroApp.findAndCountAll({
      attributes: ['id', 'name', 'entry', 'activeRule', 'childProps', 'code'],
    });
    if (!list) {
      res.send({ errcode: 1, msg: '查询失败', success: false });
    }
    res.send({ errcode: 0, msg: 'ok', data: list, success: true });
  } catch (error) {
    console.log('服务错误:', error);
    res.send({ errcode: 1, msg: '查询失败' + error, success: true });
  }
};
const editMicroApp = async (req, res) => {
  console.log('编辑微应用配置');
  const { id, name, entry, activeRule, childProps, code } = req.body;
  try {
    const [flag, MicroInfo] = await MicroApp.update({ name, entry, activeRule, childProps, code }, { where: { id } });
    if (flag) {
      res.send({ errcode: 0, msg: 'ok', success: true });
    } else {
      res.send({ errcode: 1, msg: '编辑失败', success: false });
    }
  } catch (error) {
    console.log('服务错误:', error);
    res.send({ errcode: 1, msg: '编辑失败' + error, success: true });
  }
};
/**
 * 删除微应用配置
 * @param {*} req
 * @param {*} res
 */
const delMicroApp = async (req, res) => {
  console.log('删除微应用配置');
  const { id } = req.body;
  try {
    const flag = await MicroApp.destroy({ where: { id } });
    if (flag) {
      res.send({ errcode: 0, msg: 'ok', success: true });
    } else {
      res.send({ errcode: 1, msg: '删除失败', success: false });
    }
  } catch (error) {
    console.log('服务错误:', error);
    res.send({ errcode: 1, msg: '删除失败' + error, success: true });
  }
};

module.exports = { addMicroApp, editMicroApp, getMicroAppList, delMicroApp };
